//
//  KoiAccountingUserManager.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
import SwiftUI

class KoiAccountingUserManager {
    
    static var standard = KoiAccountingUserManager()
    
    private var mUser:KoiAccountingUser?
    
    init () {
        // 在登录成功之后，本地缓存已有用户数据，所以只要在 init 中初始化即可
        mUser = KoiUserLocalData.getUser()
    }
    
    func userId() -> String {
        let uid = mUser?.uid
        return uid.orEmpty
    }
    
    func user() -> KoiAccountingUser? {
        return mUser
    }
    
    func isLoggedIn() -> Bool {
        return mUser != nil
    }
    
    func isNeedInit() -> Bool {
        return KoiAccountingData.isNeedInit(uid: userId())
    }
    
    func isTrail() -> Bool {
        return user()?.isTrialLogin() == true
    }
    
    func updateUser(
        nickname: String? = nil,
        phone: String? = nil,
        age: Int? = nil,
        gender: Int? = nil,
        hasPw: Int? = nil,
        wxProfile: KoiWxProfile? = nil
    ) {
        if let nickname = nickname {
            mUser?.nickname = nickname
        }
        if let phone = phone {
            mUser?.phone = phone
        }
        if let age = age {
            mUser?.age = age
        }
        if let gender = gender {
            mUser?.sex = gender
        }
        if let hasPw = hasPw {
            mUser?.hasPw = hasPw
        }
        if let wxProfile = wxProfile {
            mUser?.wxProfile = wxProfile
        }
        guard let user = mUser else {
            return
        }
        KoiUserLocalData.saveUser(user:user)
    }
    
    
    func updateUser(user: KoiAccountingUser?) {
        if let user = user {
            mUser = user
            KoiUserLocalData.saveUser(user: user)
        }
    }
    
    func updateNeedInit(isNeedInit: Int) {
        mUser?.isInit = isNeedInit
        if let user = mUser {
            KoiUserLocalData.saveUser(user: user)
        }
    }
    
    // 登录成功，保存用户信息
    func login(user:KoiAccountingUser?) {
        guard let user = user else {
            return
        }
        mUser = user
        KoiUserLocalData.saveUser(user:user)
        KoiAccountingData.saveNeedInit(uid: userId(), needInit: user.isNeedInit())
        KoiTokenStore.saveAccessToken(token: user.accessToken)
        KoiTokenStore.saveRefreshToken(token: user.refreshToken)
        KoiTokenStore.saveAccessTokenExp(exp: user.accessTokenExp)
    }
    
    // 退出登录
    func logout() {
        // 保存上一个用户的登录信息，用户下次快速登录
        KoiUserLocalData.saveLastLoginUser()
        // 删除登录用户
        KoiUserLocalData.removeUser()
        // 删除登录 token
        KoiTokenStore.removeToken()
    }
    
    func accessToken() -> String {
        return KoiTokenStore.getAccessToken()
    }
    
    func testLoginState(appState: AppState) {
        appState.isLoggedIn.toggle()
    }
}
